const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const koaBody = require('koa-body');
const logger = require('koa-logger');
const onerror = require('koa-onerror')
const moment = require('moment');
const path = require('path');
const render = require('koa-art-template');//模板引擎

const mount = require('koa-mount')
const server = require('koa-static')
// 接口引入
// const Home = require('./routes/v1/index');
// app.use(async ctx => {
//   ctx.body = 'Hello World';
// });
// app.use(Home.routes(),Home.allowedMethods());

// 使用require-directory加载路由文件夹下的所有router
const requireDirectory = require('require-directory');


// 接受传参form-data格式 以及文件
app.use(koaBody({
    multipart:true,//支持文件上传，
    encoding:'gzip'
  }))
//   公共可访问静态资源
  app.use(mount('/public',server(__dirname + '/public')))
  app.use(logger(str => {
    console.log(moment().format('YYYY-MM-DD HH:mm:ss') + str)
  }))
  // logger
  onerror(app);

  render(app, {
    root: path.join(__dirname, './views'),
    extname: '.art',
    debug: process.env.NODE_ENV !== 'production'
  });

//需要放在路由前监听所有 洋葱圈
app.use(async (ctx, next) => {
     
    try {
      const start = new Date()
      await next()
      const ms = new Date() - start
      const currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
      console.log(`${ctx.method} ${ctx.url} - ${ms}ms 时间：${currentTime}`)
    } catch (error) {
      // console.log(error)
      ctx.response.status = 501;
      ctx.body = {
          code: 0,
          data: error
      }
    }
   
    // console.log(ctx.request.method)

    // console.log(ctx.query)
    // console.log(ctx.request.body)
    // console.log(ctx.request.files)
  })

// console.log(process.cwd()) 在路由中间件和koa-body都存在的情况下，务必让koa-body在koa-router之前。否则会报错。
const modules = requireDirectory(module, './routes/v1', { visit: whenLoadModule })
function whenLoadModule(obj) {
  if (obj instanceof Router) {
    app.use(obj.routes(), obj.allowedMethods())
  }
}

app.listen(3000);

app.on('error', (err, ctx) => {
    // console.log('server error', err, ctx)
    ctx.response.status = 500;
    ctx.body = {
        code: 0,
        data: err
    }
});